﻿//将方法包装到一个对象下，相当于命名空间，避免重复
var wmsCommon = new Object();

wmsCommon.getCurrentURI = function () {
    return document.URL;
}

//获取当前站点或 虚拟目录 的路径
wmsCommon.getRootPath = function () {
    var strFullPath = window.document.location.href;
    var strPath = window.document.location.pathname;
    var pos = strFullPath.indexOf(strPath);
    var prePath = strFullPath.substring(0, pos);
    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    return (prePath + postPath);
}

wmsCommon.getAllQueryString = function () {
    var url = wmsCommon.getCurrentURI();
    var index = url.indexOf('?');
    if (index == -1)

        return "";
    url = url.substring(index + 1, url.length);

    return url
}


//得到查询字符串键值对。
wmsCommon.getQueryString = function () {
    var url = wmsCommon.getCurrentURI();
    var index = url.indexOf('?');
    if (index == -1)
        return "";
    url = url.substring(index + 1, url.length);

    var queryString = new Array();
    var reg = /([^=&]*)=([^&]*)/g;
    var m;
    while ((m = reg.exec(url)) != null) {
        queryString[m[1]] = decodeURI(m[2]);
    }
    return queryString;
}

//得到查询字符串中对应键的值
wmsCommon.getQueryValue = function (key) {
    try {
        return wmsCommon.getQueryString()[key];
    }
    catch (e) {
        return "";
    }
}

//通过查询字符串数组，构造新的URI。
wmsCommon.rebuildURI = function (queryString) {
    var uri = wmsCommon.getCurrentURI();
    var index = uri.indexOf('?');
    if (index != -1)
        uri = uri.substring(0, index + 1);
    for (var key in queryString) {
        uri += key + '=' + encodeURI(queryString[key]) + '&';
    }
    if (uri.lastIndexOf('&') == uri.length - 1)
        uri = uri.substr(0, uri.length - 1);
    return uri;
}


//获取当前页面列表中选中的行
wmsCommon.getSelectedItems = function () {
    var list = new Array();
    for (var i = 0; i < currentModel.length; i++) {
        var row = currentModel[i];
        if (row.checked != undefined && row.checked == true)
            list[list.length] = row;
    }
    return list;
}

//执行数据获取命令
wmsCommon.execCommand = function (expr, query) {
    var result;
    var srvUrl = wmsCommon.getRootPath() + '/Service/CommonService.asmx/ExecCommand?';
    srvUrl += (query != undefined) ? query : "";
    jQuery.ajax({
        type: 'POST',
        url: srvUrl,
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: "{expr:\"" + expr + "\"}",
        success: function (data) {
            result = data.d;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            wmsCommon.showError(XMLHttpRequest.responseText);
        }
    });
    if (result == "timeOut") {
        alert("链接超时,请重新登录!");
        wmsCommon.closeWinWithCtrParentWin("Login.aspx");
        return result;
    } else {
        return result;
    }
}

//对当前页面数据进行排序
wmsCommon.sort = function (colName, sortExpr) {
    var query = wmsCommon.getQueryString();
    var orderby = query["orderby"];
    // 如果url里存在排序条件
    if (orderby != undefined) {
        var arr = orderby.split(',')
        var item;
        var sortItem = sortExpr.split(' ');
        var exists = false;
        for (var i = 0; i < arr.length; i++) {
            item = arr[i].split(' ');
            if (item[0] == sortItem[0]) {
                if (item[1] == 'desc')
                    item[1] = 'asc';
                else
                    item[1] = 'desc';

                //  Midify by tianp 当前点击列作为排序的第一列
                arr[i] = item[0] + " " + item[1];
                var index = arr[0];
                arr[0] = arr[i];
                arr[i] = index;

                exists = true;
                break;
            }
        }
        if (exists)
            query["orderby"] = arr.join(',');
        else
            query["orderby"] = sortExpr + "," + query["orderby"];
    }
    else {
        query["orderby"] = sortExpr;
    }
    document.URL = wmsCommon.rebuildURI(query);
}

//根据表单控件信息，执行查询
wmsCommon.search = function () {
    var condExpr = jQuery('#form1').formSerialize();
    var query = wmsCommon.getQueryString();
    query["query"] = wmsCommon.getCondExpr(condExpr);
    document.location = wmsCommon.rebuildURI(query);
}

wmsCommon.delrows = function (id) {
    if (confirm("是否确认删除")) {
        var expr = "sys(#DataModelManager.DelModel(" + modelName + "," + idStr + "))";
        var data = wmsCommon.execCommand(expr);
        if (data.d) {
            index = 0;
            var queryStr = jQuery('#form1').formSerialize();
            InitTotalInfo(queryStr);
            var pg = $('#Pagination');
            if (pg.length > 0)
                pg.trigger('setPage', [0]);

        }
    }
}

//根据表单信息，调用后台方法，得到查询条件
wmsCommon.getCondExpr = function (expr) {
    var modelName = wmsCommon.getQueryValue('model');
    if (modelName == undefined)
        return undefined;
    else {
        var result;
        var rootPath = wmsCommon.getRootPath();
        jQuery.ajax({
            type: 'POST',
            url: rootPath + '/Service/CommonService.asmx/GetQueryCond',
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: "{modelName:\"" + modelName + "\",expr:\"" + expr + "\"}",
            success: function (data) {
                result = data.d;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                wmsCommon.showError(XMLHttpRequest.responseText);
            }

        });
        if (result == "timeOut") {
            alert("链接超时,请重新登录!");
            wmsCommon.closeWinWithCtrParentWin("Login.aspx");
        }
        else
            return result;
    }
}

//根据key得到session的值
wmsCommon.getSessionValue = function (key) {
    //debugger;
    var result;
    var rootPath = wmsCommon.getRootPath();
    jQuery.ajax({
        type: 'POST',
        url: rootPath + '/Service/CommonService.asmx/GetStoreValue',
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: "{storeType:\"session\",key:\"" + key + "\"}",
        success: function (data) {
            result = data.d;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            wmsCommon.showError(XMLHttpRequest.responseText);
        }

    });
    return result;
}
//得到cache的值   使用时需做能做为空验证
wmsCommon.getCacheValue = function (key) {
    var result;
    var rootPath = wmsCommon.getRootPath();
    jQuery.ajax({
        type: 'POST',
        url: rootPath + '/Service/CommonService.asmx/GetStoreValue',
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: "{storeType:\"cache\",key:\"" + key + "\"}",
        success: function (data) {
            result = data.d;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            wmsCommon.showError(XMLHttpRequest.responseText);
        }

    });
    return result;
}

//获取config配置
wmsCommon.getConfig = function (conf) {
    var result;
    var rootPath = wmsCommon.getRootPath();
    jQuery.ajax({
        type: 'POST',
        url: rootPath + '/Service/CommonService.asmx/GetConfig',
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: "{conf:'" + conf + "'}",
        success: function (data) {
            result = data.d;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            wmsCommon.showError(XMLHttpRequest.responseText);
        }
    });
    if (result == "timeOut") {
        alert("链接超时,请重新登录!");
        wmsCommon.closeWinWithCtrParentWin("Login.aspx");
        return;
    }
    else
        return result;
}
//退出 释放用户信息
wmsCommon.unloadUserMsg = function () {
    var expr = "sys(#UserManager.UnloadCurrentUser())";
    var data = wmsCommon.execCommand(expr);
}

wmsCommon.getSelectedKeyValues = function (tableid) {
    if (tableid.length == 0) tableid = "contenttb";
    var idStr = "";
    $('#' + tableid + ' tr:gt(0)').each(function () {
        var element = $(this).find("td:first>input"); //
        if (element.attr("type") == "checkbox" && element.attr("checked")) {
            idStr += element[0].parentNode.parentNode.attributes["keyvalue"].value + ",";
        }
    });
    if (idStr.length > 0) {
        idStr = idStr.slice(0, idStr.length - 1);
    }
    return idStr;
    //    if (tableid.length == 0) tableid = "contenttb";
    //    var inputList = jQuery('#' + tableid + ' tr td input');
    //    var idStr = "";
    //    for (var i = 0; i < inputList.length; i++) {
    //        if (inputList[i].type == "checkbox") {
    //            if (inputList[i].checked) {
    //                idStr += inputList[i].parentNode.parentNode.attributes["keyvalue"].value + ",";
    //            }
    //        }
    //    }
    //    if (idStr.length > 0) {
    //        idStr = idStr.slice(0, idStr.length - 1);
    //    }
    //    return idStr;
}
//  列表全选方法
//检查字符是否为null
wmsCommon.checkForNull = function (str) {
    if (str != undefined && str != null && str != "")
        return str;
    else
        return "";
}
wmsCommon.beforeSave = function (modelName, jsonStr, opt) {
    return true;
}

wmsCommon.afterSave = function (modelName, jsonStr, opt) {
    return true;
}

///默认保存方法,如果后代要实现自己的保存方法,则覆盖该方法
wmsCommon.saveMethod = function (query) {
    //    debugger;
    var opt = wmsCommon.getQueryValue("opt");
    var modelName = wmsCommon.getQueryValue("model");
    var jsonStr = jQuery('#form1').formSerialize();
    //保存前事件
    if (!wmsCommon.beforeSave(modelName, jsonStr, opt))
        wmsCommon.showDialog("保存前事件失败，请联系管理员！");
    else {
        if (wmsCommon.execCommand(String.format("sys(#DataModelManager.SaveModel({0},{1},{2}))", modelName, jsonStr, opt), query) == "")
            wmsCommon.showDialog("保存失败，请联系管理员！");
        else {
            if (wmsCommon.afterSave(modelName, jsonStr, opt) == "")
                wmsCommon.showDialog("保存后事件失败，请联系管理员！");
            else {
                if (confirm("保存成功,确认关闭")) {
                    window.close();
                    if (window.opener.parent) {
                        wmsCommon.refPParentWinPage();
                    } else {//暂时
                        wmsCommon.refParentWinPage();
                    }
                }
            }
        }
    }
}


///删除方法,如果后代实现可改写
wmsCommon.delMethod = function () {
    var idStr = wmsCommon.getSelectedKeyValues();
    if (confirm("是否确认删除?")) {
        var expr = "sys(#DataModelManager.DelModel(" + modelName + "," + idStr + "))";
        wmsCommon.execCommand(expr);
        window.location.reload();
    }
}


//将js对象转化为json串
wmsCommon.objToJsonStr = function (obj) {
    var r = [];
    if (typeof obj == "string") return "\"" + obj.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
    if (typeof obj == "object") {
        if (!obj.sort) {
            for (var i in obj)
                r.push(i + ":" + wmsCommon.objToJsonStr(obj[i]));
            if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(obj.toString)) {
                r.push("toString:" + obj.toString.toString());
            }
            r = "{" + r.join() + "}"
        } else {
            for (var i = 0; i < obj.length; i++)
                r.push(wmsCommon.objToJsonStr(obj[i]))
            r = "[" + r.join() + "]"
        }
        return r;
    }
    return obj.toString();
}

//功能：以Open方式打开窗口
//参数：sFile	-	页面文件路径
//		sWidth	-	窗口宽度
//		sHeight -	窗口高度
//		sType	-	打开方式
//					0 - 以设定大小打开
//					1 - 以自适应窗口大小打开
wmsCommon.openWin = function (sFile, sWidth, sHeight, sType) {
    if (wmsCommon.getSessionValue("userNo") == "") {
        wmsCommon.timeOut();
        return;
    }
    if (sType == undefined || sType == null || sType == "") sType = 0;
    if (sType == 0) {
        var iX = screen.width - 10;
        var iY = screen.height - 55;
        var iTop, iLeft;
        iTop = (iY - sHeight) / 2;
        iLeft = (iX - sWidth) / 2;
        window.open(sFile, "_blank", "top=" + iTop + ",left=" + iLeft + ",width=" + sWidth + ",height=" + sHeight + ",status=1,resizable=1");
    }
    else {
        var iX = screen.width - 10;
        var iY = screen.height - 55;
        window.open(sFile, "_blank", "top=0,left=0,width=" + iX + ",height=" + iY + ",status=1,resizable=1");
    }
}


//功能：用showModalDialog打开窗口
//		sFile		-	页面文件路径
//		sWidth		-	窗口宽度
//		sHeight		-	窗口高度
//		sType		-	打开方式 //					0 - 以设定大小打开 		1 - 以自适应窗口大小打开
//返回：窗口关闭后的返回值
wmsCommon.openModalWin = function (url, sWidth, sHeight, strdialogArguments) {
    if (wmsCommon.getSessionValue("userNo") == "") {
        wmsCommon.timeOut();
        return;
    }
    var sBackValue;
    var screamSize = "dialogHeight:" + sHeight + "px; dialogWidth:" + sWidth + "px; help:no; status:no;scroll:no;"
    if (url == undefined || url == null) return;
    if (strdialogArguments != undefined) {
        sBackValue = window.showModalDialog(url, strdialogArguments, screamSize);
    }
    else {
        sBackValue = window.showModalDialog(url, "", screamSize);
    }
    return sBackValue;
}


wmsCommon.timeOut = function () {
    alert("链接超时,请重新登录!");
    window.parent.parent.parent.parent.location.href = "Login.aspx";
}



//功能同上
wmsCommon.addModalOpen = function (model, template, sWidth, sHeight, strdialogArguments) {
    //    debugger;
    if (wmsCommon.getSessionValue("userNo") == "") {
        wmsCommon.timeOut();
        return;
    }
    var sBackValue;
    var rootPath = wmsCommon.getRootPath();
    var url = rootPath + "/Model.aspx?model=" + model + "&temp=" + template + "&opt=1";
    var screamSize = "dialogHeight:" + sHeight + "px; dialogWidth:" + sWidth + "px; help:no; status:no;scroll:no;"
    if (url == undefined || url == null) return;
    if (strdialogArguments != undefined) {
        sBackValue = window.showModalDialog(url, strdialogArguments, screamSize);
    }
    else {
        sBackValue = window.showModalDialog(url, "", screamSize);
    }
    return sBackValue;
}

wmsCommon.closeWin = function () {
    if (confirm("是否确认关闭?")) window.close();
}
//jquery 弹出提示框;
wmsCommon.showDialog = function (message) {
    if (message)
        alert(message);
    else
        alert("操作失败！请与管理员联系！");
    //debugger;
    //    $("#dialog-confirm").text(message);
    //    $("#dialog-confirm").dialog({
    //        resizable: false,
    //        height: 140,
    //        modal: true,
    //        buttons: {
    //            "关闭": function () {
    //                $(this).dialog("close");
    //            }
    //        }
    //    });
}

//存库编辑列表样式新增行模板
wmsCommon.rowTemp = new Array();

///处理新增行字符串
wmsCommon.processnewRowStr = function (tableid, data) {
    //    debugger;
    var rowcount = $('#' + tableid + ' tr').length + 1;
    var re = new RegExp("\\$-1", "g");
    data = data.replace(re, '$' + rowcount);
    return $.trim(data);
}

//新增列表样式编辑行
//tableid 列表编辑table id
wmsCommon.newRow = function (tableid) {
    var data;
    if (!wmsCommon.rowTemp[tableid]) {
        data = wmsCommon.execCommand("sys(#DataModelManager.GetNewRow(" + wmsCommon.getQueryValue('model') + "," + wmsCommon.getQueryValue('temp') + "," + tableid + "))", "model=" + tableid+"&opt=1");
        wmsCommon.rowTemp[tableid] = data;
    }
    else {
        data = wmsCommon.rowTemp[tableid];
    }
    $('#' + tableid + '').append(wmsCommon.processnewRowStr(tableid, data));
}


//  列表全选方法
//  tableId ：table 的ID
//  iCells ： 指定chencBox 所在的列，如果为空，默认为第一列
wmsCommon.checkedAll = function (tableId, intCells) {
    var ifChecked = true;
    var table = document.getElementById(tableId);
    if (table.rows.length <= 1) return;
    if (wmsCommon.checkForNull(intCells) == "") {
        intCells = 0;
    }
    //在table中添加 属性记录上次被选中状态
    if (table.checkedAll == undefined) {
        table.setAttribute("checkedAll", "true")
    }
    if (table.checkedAll != "true") {
        ifChecked = false;
        table.checkedAll = "true";
    }
    else {
        table.checkedAll = "false";
    }
    for (var i = 1; i < table.rows.length; i++) {
        if (table.rows[i].cells[intCells].childNodes[0].type == "checkbox") {
            table.rows[i].cells[intCells].childNodes[0].checked = ifChecked;
            table.rows[i].bgColor = (ifChecked ? "#D8E1F9" : "#FFFFFF");
        }
    }
}
//页面通用方法
//保存方法，保存成功后返回主表主键值
//  dataModel : xml模型名称
wmsCommon.pubSaveMethod = function (dataModel, query) {
    var opt = wmsCommon.getQueryValue("opt");
    var jsonStr = jQuery('#form1').formSerialize();
    var rtn = wmsCommon.execCommand(String.format("sys(#DataModelManager.SaveModel({0},{1},{2}))", dataModel, jsonStr, opt), query);
    return rtn;
}

//保存并刷新
wmsCommon.pubSaveAndRefPage = function (dataModel, query) {
    rtn = wmsCommon.pubSaveMethod(dataModel, query);
    if (wmsCommon.checkForNull(rtn) != "") {
        if (confirm("保存成功！  是否关闭窗口？")) {
            wmsCommon.refParentPage();
            window.close();
        }
        else {
            wmsCommon.refPage(rtn);
        }
    } else {
        wmsCommon.alert("保存失败，请与管理员联系！");
    }

}


//打开新增界面   model:对应的xml模型名称  temp: html模板名称
wmsCommon.openAddWin = function (model, temp, width, hight, urlParameter) {
    //    if (wmsCommon.getSessionValue("userNo") == "") {
    //        wmsCommon.timeOut();
    //        return;
    //    }
    if (wmsCommon.checkForNull(width) == "") width = 800;
    if (wmsCommon.checkForNull(hight) == "") hight = 600;
    var rootPath = wmsCommon.getRootPath();
    if (urlParameter) {
        wmsCommon.openWin(rootPath + "/model.aspx?opt=1&model=" + model + "&temp=" + temp + "&" + urlParameter, width, hight);
    } else {
        wmsCommon.openWin(rootPath + "/model.aspx?opt=1&model=" + model + "&temp=" + temp, width, hight);
    }
}



//或 列表行中的主键信息作为参数 打开窗口
//parm 例: userno=900990 将该参数加入到url中
wmsCommon.openParamWin = function (model, temp, width, hight, parm) {
    if (wmsCommon.getSessionValue("userNo") == "") {
        wmsCommon.timeOut();
        return;
    }
    if (wmsCommon.checkForNull(obj) == "") return;
    wmsCommon.openAddWin(model, temp, width, hight, parm);
}
//修改   obj:修改按钮 （一般用this） model:对应的xml模型名称  temp: html模板名称
wmsCommon.openModifyWin = function (obj, model, temp, width, hight) {
    //    if (wmsCommon.getSessionValue("userNo") == "") {
    //        wmsCommon.timeOut();
    //        return;
    //    }
    if (wmsCommon.checkForNull(obj) == "") return;
    var parentNd = obj.parentNode.parentNode;
    var keyValue = parentNd.keyvalue;
    if (wmsCommon.checkForNull(keyValue) == "") keyValue = parentNd.parentNode.keyvalue
    if (wmsCommon.checkForNull(keyValue) == "") return;
    if (wmsCommon.checkForNull(width) == "") width = 900;
    if (wmsCommon.checkForNull(hight) == "") hight = 600;
    var rootPath = wmsCommon.getRootPath();
    wmsCommon.openWin(rootPath + "/model.aspx?opt=2&model=" + model + "&temp=" + temp + "&primary=" + encodeURI(keyValue), width, hight);
    //下面是模态窗口打开
    //OpenModalWin("../model.aspx?opt=2&model=orderCommon&temp=orderCommonInfo_edit&keyvalue=" + encodeURI(keyValue), 800, 600);
}

//修改且包含事件   obj:修改按钮 （一般用this） model:对应的xml模型名称  temp: html模板名称
wmsCommon.openModifyWinWithEvent = function (obj, model, temp, eventName, eventSys, width, hight) {
    //    if (wmsCommon.getSessionValue("userNo") == "") {
    //        wmsCommon.timeOut();
    //        return;
    //    }

    if (wmsCommon.checkForNull(obj) == "") return;
    var parentNd = obj.parentNode.parentNode;
    var keyValue = parentNd.keyvalue;
    if (wmsCommon.checkForNull(keyValue) == "") keyValue = parentNd.parentNode.keyvalue
    if (wmsCommon.checkForNull(keyValue) == "") return;
    if (wmsCommon.checkForNull(width) == "") width = 900;
    if (wmsCommon.checkForNull(hight) == "") hight = 600;
    var rootPath = wmsCommon.getRootPath();
    wmsCommon.openWin(rootPath + "/model.aspx?opt=2&model=" + model + "&temp=" + temp + "&" + eventName + "=" + escape(eventSys) + "&primary=" + encodeURI(keyValue), width, hight);
    //下面是模态窗口打开
    //OpenModalWin("../model.aspx?opt=2&model=orderCommon&temp=orderCommonInfo_edit&keyvalue=" + encodeURI(keyValue), 800, 600);
}


//打开新增界面   model:对应的xml模型名称  temp: html模板名称
wmsCommon.openAddWinWithEvent = function (model, temp, eventName, eventSys, width, hight, urlParameter) {
    //    if (wmsCommon.getSessionValue("userNo") == "") {
    //        wmsCommon.timeOut();
    //        return;
    //    }
    if (wmsCommon.checkForNull(width) == "") width = 800;
    if (wmsCommon.checkForNull(hight) == "") hight = 600;
    var rootPath = wmsCommon.getRootPath();
    if (urlParameter) {
        wmsCommon.openWin(rootPath + "/model.aspx?opt=1&model=" + model + "&temp=" + temp + "&" + eventName + "=" + escape(eventSys) + "&" + urlParameter, width, hight);
    } else {
        wmsCommon.openWin(rootPath + "/model.aspx?opt=1&model=" + model + "&temp=" + temp + "&" + eventName + "=" + escape(eventSys), width, hight);
    }
}

//修改   obj:修改按钮 （一般用this） model:对应的xml模型名称  temp: html模板名称   此方法与上方法不同之处是  参数：keyValue 是直接参数，非，html对象
wmsCommon.openModifyWinWithKey = function (keyValue, model, temp, width, hight) {
    //    if (wmsCommon.getSessionValue("userNo") == "") {
    //        wmsCommon.timeOut();
    //        return;
    //    }
    if (wmsCommon.checkForNull(keyValue) == "") keyValue = parentNd.parentNode.keyvalue
    if (wmsCommon.checkForNull(keyValue) == "") return;
    if (wmsCommon.checkForNull(width) == "") width = 900;
    if (wmsCommon.checkForNull(hight) == "") hight = 600;
    var rootPath = wmsCommon.getRootPath();
    wmsCommon.openWin(rootPath + "/model.aspx?opt=2&model=" + model + "&temp=" + temp + "&primary=" + encodeURI(keyValue), width, hight);
    //下面是模态窗口打开
    //OpenModalWin("../model.aspx?opt=2&model=orderCommon&temp=orderCommonInfo_edit&keyvalue=" + encodeURI(keyValue), 800, 600);
}


//修改   obj:修改按钮 （一般用this） model:对应的xml模型名称  temp: html模板名称
wmsCommon.openLookWin = function (keyvalue, model, temp, width, hight) {
    if (wmsCommon.getSessionValue("userNo") == "") {
        wmsCommon.timeOut();
        return;
    }
    if (wmsCommon.checkForNull(keyvalue) == "") return;
    if (wmsCommon.checkForNull(temp) == "") return;
    if (wmsCommon.checkForNull(model) == "") return;
    if (wmsCommon.checkForNull(width) == "") width = 800;
    if (wmsCommon.checkForNull(hight) == "") hight = 600;
    var rootPath = wmsCommon.getRootPath();
    wmsCommon.openWin(rootPath + "/model.aspx?opt=3&model=" + model + "&temp=" + temp + "&primary=" + encodeURI(keyvalue), width, hight);
}

//删除  tableID:删除表的ID
// modelName：主表模型名称 
//cnModelName  业务模块名称
wmsCommon.deleteRows = function (tableID, modelName, cnModelName) {
    var allSelectedRow = wmsCommon.getSelectedKeyValues(tableID);
    if (wmsCommon.checkForNull(allSelectedRow) != "") {
        if (confirm("是否确定要删除选择的信息？")) {
            var keyColumns = allSelectedRow.replace(/,/g, "|");
            var ifSucc = wmsCommon.execCommand(String.format("sys(#CommonFunction.CommonDeleteDate({0},{1}))", keyColumns, modelName));
            if (ifSucc == "OK") {
                wmsCommon.createActionLog(cnModelName, "删除", keyColumns);
                wmsCommon.refThisPage();
                return true;
            }
            else if (ifSucc == "timeOut") {
                alert("连接超时，请重新登陆！");
            }
            else {
                wmsCommon.alert("删除操作失败，请与管理员联系！");
            }
        }
    }
    else {
        wmsCommon.alert("请先选择需要删除的信息！");
    }
}

//带联合主键的删除  tableID:删除表的ID，modelName：主表模型名称
wmsCommon.deleteRecords = function (tableID, modelName) {
    var allSelectedRow = wmsCommon.getSelectedKeyValues(tableID);
    if (wmsCommon.checkForNull(allSelectedRow) != "") {
        if (confirm("是否确定要删除选择的信息？")) {
            allSelectedRow = allSelectedRow.replace(/,/g, "|");
            var ifSucc = wmsCommon.execCommand(String.format("sys(#CommonFunction.CommonDeleteRecords({0},{1}))", allSelectedRow, modelName));
            if (ifSucc == "OK") {
                wmsCommon.refThisPage();
            }
            else if (ifSucc == "timeOut") {
                //alert("连接超时，请重新登陆！");
            }
            else {
                wmsCommon.alert("删除操作失败，请与管理员联系！");
            }
        }
    }
    else {
        wmsCommon.alert("请先选择需要删除的信息！");
    }
}
//无子表 字段名关联删除
//tblID 页面标id,
//modelNameList: 让删除的模板名称串,用逗号分隔
// promptText: 附加特殊提示信息
wmsCommon.relatedDelete = function (tblID, modelNameList, promptText) {
    if (promptText == "") {
        promptText = "是否确定删除选择行的关联信息";
    }
    var allSelectedRow = wmsCommon.getSelectedKeyValues(tblID);
    if (wmsCommon.checkForNull(allSelectedRow) == "" || wmsCommon.checkForNull(modelNameList) == "") {
        alert("请选择删除信息!");
        return;
    }
    else {
        if (confirm("是否确定要删除选择行")) {
            if (confirm(promptText)) {
                var ifSucc = wmsCommon.execCommand(String.format("sys(#CommonFunction.CascadeDelete({0},{1}))", escape(allSelectedRow), escape(modelNameList)));
                if (ifSucc == "OK") {
                    alert("删除成功!");
                }
                else {
                    alert("删除失败!");
                }
                wmsCommon.refParentPage();
            }
        }
    }
}

//单表的删除 tableName：表名称  tableID:删除表的ID
wmsCommon.DeleteSingleDate = function (tableID, tblName) {
    //debugger;

    var userNo = wmsCommon.getSessionValue("userNo");
    if (wmsCommon.checkForNull(userNo) == "") {
        alert("登录信息过期，请重新登录！");
        return;
    }

    var allSelectedRow = wmsCommon.getSelectedKeyValues(tableID);
    if (wmsCommon.checkForNull(allSelectedRow) != "") {
        if (confirm("是否确定要删除选择的信息？")) {
            allSelectedRow = allSelectedRow.replace(/,/g, "|");
            var ifSucc = wmsCommon.execCommand(String.format("sys(#CommonFunctions.DeleteSingleDate({0},{1}))", tblName, allSelectedRow));
            if (ifSucc == "OK") {
                wmsCommon.refThisPage();
            }
            else {
                wmsCommon.alert("删除操作失败，请与管理员联系！");
            }
        }
    }
    else {
        wmsCommon.alert("请先选择需要删除的信息！");
    }
}


/*弹框美化
title:        标题
contentHtml:  内容，可以是html
refresh:      点关闭按钮时是否刷新页面 0 不刷新、1 刷新
iWidth:       弹框的宽度
iHeight       弹框的高度
*/
wmsCommon.popHtml = function (title, contentHtml, refresh, iWidth, iHeight) {
    if (title == "") title = "消息";
    if (iWidth == "") iWidth = 700;
    if (iHeight == "") iHeight = 300;
    if (refresh == "") refresh = 0;
    var pop = new Popup({ contentType: 2, isReloadOnClose: false, width: iWidth, height: iHeight });
    pop.setContent("contentHtml", contentHtml);
    pop.setContent("title", title);
    pop.build();
    pop.show();
    document.all("dialogBoxClose").refresh = refresh;
    document.all("btnClose").refresh = refresh;
}

wmsCommon.popAlert = function (title, alertCon, iWidth, iHeight) {
    //    if (title == "") title = "消息";
    //    if (iWidth == "") iWidth = 340;
    //    if (iHeight == "") iHeight = 80;
    //    var pop = new Popup({ contentType: 4, isReloadOnClose: false, width: iWidth, height: iHeight });
    //    pop.setContent("title", title);
    //    pop.setContent("alertCon", alertCon);
    //    pop.build();
    //    pop.show();
    alert(alertCon);
}

wmsCommon.alert = function (context) {
    //    var title = "警告";
    //    var iWidth = 340;
    //    var iHeight = 80;
    //    wmsCommon.popAlert(title, context, iWidth, iHeight);
    alert(context);
}




//刷新本页面和父页面
wmsCommon.refPage = function (rtn) {
    wmsCommon.refThisPage(rtn);
    wmsCommon.refParentPage();
}
//刷新本页面
// opt:1表示新增  2表示修改
//rtn：表示 主键值表达式
wmsCommon.refThisPage = function (rtn) {
    if (wmsCommon.checkForNull(rtn) == "") {
        window.location = window.location;
    }
    else {
        var opt = wmsCommon.getQueryValue("opt");
        if (opt == "1") {  //如果是新增，保存之后opt要变成2
            try {
                var url = window.location.href;
                url = url.replace("opt=1", "opt=2");
                url = url + encodeURI("&primary=" + rtn);
                window.location.href = url;
            } catch (e) { }
        } else {
            window.location = window.location;
        }
    }
}
//刷新父窗体
wmsCommon.refParentWinPage = function () {
    window.opener.location.href = window.opener.location.href;
}
//刷新父窗体的框架窗体
wmsCommon.refPParentWinPage = function () {
    window.opener.parent.location.href = window.opener.parent.location.href;
}
//刷新父页面
wmsCommon.refParentPage = function () {
    try {
        if (wmsCommon.checkForNull(window.opener) != "" && wmsCommon.checkForNull(window.opener.location) != "") {
            window.opener.location = window.opener.location;
        }
        else if (wmsCommon.checkForNull(window.parent) != "" && wmsCommon.checkForNull(window.parent.location) != "") {
            window.parent.location = window.parent.location;
        }
    } catch (e) { }
}

//验证session key 是否存在
wmsCommon.validateSession = function (key) {
    //debugger;
    if (wmsCommon.getSessionValue(key) == "") {
        return false;
    }
    else
        return true;

}
//获取 encodeURIComponent加密的 url参数值
wmsCommon.getEncodeQueryStr = function (key) {
    var queryStrValue = "";
    var url = decodeURIComponent(document.location.href);
    var queryStringlist = url.split('&');
    for (var i = 0; i < queryStringlist.length; i++) {
        if (queryStringlist[i].indexOf(key) > -1) {
            queryStrValue = queryStringlist[i].split('=')[1];
            break;
        }
    }
    return queryStrValue;
}

wmsCommon.searchContentCtr = function () {
    var searchID = document.getElementById("tblSearch");
    if (searchID != null) {
        if (searchID.style.display == "none") {
            searchID.style.display = "";
            document.all("image2").src = "res/images/display.gif";
        }
        else {
            searchID.style.display = "none";
            document.all("image2").src = "res/images/hidden.gif";
        }
        if (document.getElementById("listDiv")) {
            var thisBody = $('body');
            var div = document.getElementById("listDiv");
            widthRent = 0.98;
            if (searchID.style.display == "none") {
                div.style.height = (thisBody.innerHeight()) - 100; //设置高度
            } else {
                div.style.height = (thisBody.innerHeight()) - 160; //设置高度
            }
            div.style.width = (thisBody.innerWidth() - 20) * widthRent;  //设置宽度
            div.style.overflowY = "scroll";
            div.style.overflowX = "auto";
        }

    }
}
//记录操作日志    create by tianp
//  modelName  业务模块  （例如收料通知、发料通知）
//  operation   操作  （例如：审核、新增）
// detail 操作详细（单据类型+单号 如：生产入库  010002）
wmsCommon.createActionLog = function (modelName, operation, detail) {
    try {
        wmsCommon.execCommand(String.format("sys(#LogManager.LogInfo({0},{1},{2}))", modelName, operation, escape(detail)));
    } catch (e) {
    }
}

//导出excel
// TableID 导出表格的ID
// ExportName 导出Excel默认名称
wmsCommon.ExportExcelByID = function (TableID, ExportName) {
    if (TableID == null || TableID == "") {
        wmsCommon.alert("请先确定导出内容!");
        return false;
    }
    if (ExportName == null) {
        ExportName = ""
    }
    var exportvalue = document.getElementById(TableID).innerHTML;
    exportvalue = escape(exportvalue);

    var ExportForm = document.createElement("FORM");
    document.body.appendChild(ExportForm);
    ExportForm.method = "POST";
    var newElement = document.createElement("input");
    newElement.setAttribute("name", "exportvalue");
    newElement.setAttribute("type", "hidden");
    ExportForm.appendChild(newElement);
    newElement.value = exportvalue;

    var newElement = document.createElement("input");
    newElement.setAttribute("name", "filename");
    newElement.setAttribute("type", "hidden");
    ExportForm.appendChild(newElement);
    newElement.value = ExportName;
    ExportForm.action = wmsCommon.getRootPath() + "/Exec/ExportExcel.aspx";
    ExportForm.target = "_blank";
    ExportForm.submit();
}
//modleName:模板名;statusComumnName:状态列名;status:应该状态值; condition:修改数据查询条件
wmsCommon.changeStatus = function (modelName, statusColumnName, status, condition) {
    try {
        return wmsCommon.execCommand(String.format("sys(#QualityCheckManager.ChangeModelDataStatus({0},{1},{2},{3}))", modelName, statusColumnName, status, condition));
    }
    catch (e) {
        return false;
    }
}
//验证数据
wmsCommon.accFocuseBlur = function (modelName, columnName, isAllowsClient, obj) {
    if (obj.attributes["ovalue"] && obj.attributes["ovalue"].value == obj.attributes["value"].value) {

    }
    else
        wmsCommon.dataValide(modelName, columnName, isAllowsClient, obj);
}
//isAllownsClient :true 表示验证数据必须存在,false: 表示验证数据应当为不存在
wmsCommon.dataValide = function (modelName, columnName, isAllowsClient, obj) {
    var keyValue = obj.value;
    if (keyValue == "") {
        return;
    }
    else {
        if (!wmsCommon.paternValide(obj)) {  //首先验证正则表达式
            alert(obj.attributes["ctitle"].value + " : " + obj.value + "  数值类型不适合，请重新输入！");
            obj.focus();
            obj.select();
            return
        }
        var result = wmsCommon.execCommand(String.format("sys(#DataValidater.ValidateData({0},{1},{2},{3}))", modelName, columnName, isAllowsClient, keyValue));
        if (result == "True" && isAllowsClient == "false") {
            //var prompetText = obj.parentNode.previousSibling
            alert(obj.attributes["ctitle"].value + " : " + obj.value + "   已存在，请重新输入！");
            obj.focus();
            obj.select();
            return;
        }
        else if (result == "False" && isAllowsClient == "true") {
            alert(obj.attributes["ctitle"].value + " : " + obj.value + "  不存在,请根据提示选择内容！");
            obj.focus();
            obj.select();
            return;
        }
    }
}

//  验证 html 控件注册的正则表达式
wmsCommon.paternValide = function (obj) {
    //debugger;
    var varlidpattern = obj.attributes["validpattern"];
    if (varlidpattern && obj.value != "") {
        var reg = new RegExp(varlidpattern.value.toString());
        if (reg.test(obj.value)) {
            return true;
        }
        else {
            return false;
        }
    }
    return true;  //没有正则 表达式的注册到控件  验证通过
}
wmsCommon.dataTypeValide = function (obj) {
    //    debugger;
    if (!wmsCommon.paternValide(obj)) {
        alert(obj.attributes["ctitle"].value + " : " + obj.value + "  内容类型不适合，请重新填写！");
        obj.focus();
    }
}
//修改用户个人信息，
wmsCommon.userModify = function () {
    var keyValue = "userNo=" + wmsCommon.getSessionValue("userNo")
    wmsCommon.openModifyWinWithKey(keyValue, "userInfo", "userInfo_modify_edit", "400", "200");
}

//关闭当前窗口,并级联操作其父页面窗口
wmsCommon.closeWinWithCtrParentWin = function (href) {
    window.close();
    if (wmsCommon.checkForNull(href) == "") {
        window.opener.parent.parent.parent.close();
    }
    else {
        if (window.opener) {
            window.opener.parent.parent.parent.location.href = href;
            return;
        }
        else {
            window.parent.parent.parent.location.href = href;
            return;
        }
    }
}

wmsCommon.showError = function (mesage) {   
    var reg = /([^:]*)\"([^,]*)/g;
    var m;
    var keyArr = "";
    if ((m = reg.exec(mesage)) != null) {
        keyArr += m[2];
    }
    wmsCommon.showDialog("错误提示 " + keyArr);
}